package com.chaofan.authsso.core.service.impl;

import com.chaofan.authsso.core.service.CacheInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.CollectionUtils;

import java.util.concurrent.TimeUnit;

/**
 * Author: Chaofan
 * Date: 2020/6/5 14:12
 * email: chaofan2685@qq.com
 */
public class RedisCacheInstanceImpl implements CacheInstance {

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public Object get(String key) {
        redisTemplate.setKeySerializer(new StringRedisSerializer());  //key使用StringRedisSerializer
        return key==null?null:redisTemplate.opsForValue().get(key);
    }

    @Override
    public boolean containsKey(String key) {
        return redisTemplate.hasKey(key);
    }

    @Override
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean set(String key, Object value, long time) {
        try {
            if(time>0){
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            }else{
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public void del(String... key) {
        if(key!=null&&key.length>0){
            if(key.length==1){
                redisTemplate.delete(key[0]);
            }else{
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }

    @Override
    public boolean expire(String key, long time) {
        try {
            if(time>0){
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
